package JUC.乐观锁;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author CKC
 * @DateTime 2021/6/3 15:32
 */
public class TestAccount {
    public static void main(String[] args) {
        Account account = new AccountUnsafe(10000);
        Account.demo(account);


        Account account1 = new AccountCAS(10000);
        Account.demo(account1);
    }

}

class AccountCAS implements Account {

    private AtomicInteger balance;

    public AccountCAS(Integer balance) {
        this.balance = new AtomicInteger(balance);
    }

    public void test() {
        int i = balance.getAndIncrement();
        balance.incrementAndGet();
    }

    @Override
    public Integer getBalance() {
        return balance.get();
    }

    @Override
    public void withdraw(Integer amount) {
        while (true) {
            int prev = balance.get();
            int next = prev - amount;
            if (balance.compareAndSet(prev, next)) {
                break;
            }
        }

    }
}


class AccountUnsafe implements Account {
    private Integer balance;//余额

    public AccountUnsafe(Integer balance) {
        this.balance = balance;
    }

    @Override
    public Integer getBalance() {
        synchronized (this) {
            return this.balance;
        }
    }

    @Override
    public void withdraw(Integer amount) {
        synchronized (this) {
            this.balance -= amount;
        }
    }
}

interface Account {
    //获取余额
    Integer getBalance();

    //取款
    void withdraw(Integer amount);

    /**
     * 方法内会启动1000个线程，每个线程做 -10元的操作
     * 如果初始余额为10000  那么正确的结果应当时0
     *
     * @param account
     */

    static void demo(Account account) {
        List<Thread> ts = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            ts.add(new Thread(() -> {
                account.withdraw(10);
            }));
        }
        long start = System.nanoTime();
        ts.forEach(Thread::start);
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        long end = System.nanoTime();
        System.out.println(account.getBalance()
                + " cost:" + (end - start) / 1000_000 + " ms");
    }


}
